package com.jack.vipmis.vip.api.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.jack.vipmis.common.web.upload.FileUploadUtils;

/**
 * 
 * @author JackLiang
 * @date 2014-8-1
 * @version 1.0
 */
public class UploadServlet extends HttpServlet {

	private static final long	serialVersionUID	= 1L;

	@SuppressWarnings("static-access")
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse resp) {
		resp.setContentType("text/json; charset=UTF-8");
		String path = null;
		OutputStream os = null;
		try {
			os = resp.getOutputStream();
			// 1、创建工厂类：DiskFileItemFactory
			DiskFileItemFactory facotry = new DiskFileItemFactory();
			String tempDir = request.getServletContext().getRealPath("/WEB-INF/temp");
			facotry.setRepository(new File(tempDir));// 设置临时文件存放目录
			// 2、创建核心解析类：ServletFileUpload
			ServletFileUpload upload = new ServletFileUpload(facotry);
			upload.setHeaderEncoding("UTF-8");// 解决上传的文件名乱码
			upload.setFileSizeMax(1024 * 1024 * 1024);// 单个文件上传最大值是1M
			upload.setSizeMax(2048 * 1024 * 1024);// 文件上传的总大小限制

			// 3、判断用户的表单提交方式是不是multipart/form-data
			boolean bb = upload.isMultipartContent(request);
			if (!bb) {
				return;
			}
			// 4、是：解析request对象的正文内容List<FileItem>
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// 5、判断是否是普通表单：打印看看
					String fieldName = item.getFieldName();// 请求参数名
					String fieldValue = item.getString("UTF-8");// 请求参数值
				} else {
					// 6、上传表单：得到输入流，处理上传：保存到服务器的某个目录中
					String fileName = item.getName();
					// 解决用户没有选择文件上传的情况
					if (fileName == null || fileName.trim().equals("")) {
						continue;
					}
					fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
					System.out.println("上传的文件名是：" + fileName);
					InputStream in = item.getInputStream();
					String newFileName = FileUploadUtils.encodingFilename(fileName);
					String savePath = makeDir(request) + newFileName;
					path = "upload/" + FileUploadUtils.datePath() + "/" + newFileName;
					OutputStream out = new FileOutputStream(savePath);
					byte b[] = new byte[1024];
					int len = -1;
					while ((len = in.read(b)) != -1) {
						out.write(b, 0, len);
					}
					in.close();
					out.close();
					item.delete();// 删除临时文件
				}
			}
			// 返回的流
			os.write(path.getBytes("utf-8"));
			os.flush();
			os.close();

		} catch (FileUploadBase.FileSizeLimitExceededException e) {
			e.printStackTrace();
		} catch (FileUploadBase.SizeLimitExceededException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	/**
	 * 
	 * @param storePath
	 * @param fileName
	 * @return
	 */
	private String makeDir(HttpServletRequest request) {
		String path = FileUploadUtils.extractUploadDir(request) + "/" + FileUploadUtils.datePath() + "/";

		File file = new File(path);
		if (!file.exists())
			file.mkdirs();
		return path;
	}

	/**
	 * 将InputStream转换成String
	 * 
	 * @param in
	 *            InputStream
	 * @return String
	 * @throws Exception
	 * 
	 */
	public static String InputStreamTOString(InputStream in) throws Exception {
		String value = "";
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = in.read(b, 0, 1024)) != -1) {
			value += new String(b, 0, len, "utf-8");
		}
		return value;
	}

}
